package com.rc.evcharger.biz.job;

import com.rc.evcharger.biz.log.ChargedProcessLogAssemble;
import com.rc.evcharger.biz.notify.NotifyStopChargeResult;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.enums.ChargePhaseEnum;
import com.rc.evcharger.common.enums.HlhtOrderStatusEnum;
import com.rc.evcharger.common.enums.PileVersionEnum;
import com.rc.evcharger.common.task.PlatformTaskEnum;
import com.rc.evcharger.common.utils.DateHelper;
import com.rc.evcharger.mapper.elec.ElecGunMapper;
import com.rc.evcharger.mapper.elec.ElecPileMapper;
import com.rc.evcharger.mapper.member.MemberInfoMapper;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.model.task.PlatformTaskSetting;
import com.rc.evcharger.model.tenant.TenantManufacturer;
import com.rc.evcharger.redis.RedChargeDataService;
import com.rc.evcharger.redis.RedOrder;
import com.rc.evcharger.redis.RedOrderService;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.OrderCostService;
import com.rc.evcharger.service.order.OrderInfoService;
import com.rc.evcharger.service.task.PlatformTaskSettingService;
import com.rc.evcharger.service.tenant.TenantManufacturerService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * 定时请求正在充电的桩的充电数据
 *
 * @author yang
 */
public class CurrentOrderJob {
    private static Logger logger = LogManager.getLogger(CurrentOrderJob.class);

    //智充运营ID
    final String ZC_OPERATORID = "MA59CU773";

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderCostService orderCostService;

    @Autowired
    private TenantManufacturerService tenantManufacturerService;

    @Autowired
    private ElecPileMapper elecPileMapper;

    @Autowired
    private ElecGunMapper elecGunMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private NotifyStopChargeResult notifyStopChargeResult;

    @Autowired
    private RedChargeDataService redChargeDataService;

    @Autowired
    private ChargedProcessLogAssemble chargedProcessLogAssemble;

    @Autowired
    private PlatformTaskSettingService platformTaskSettingService;

    @Autowired
    private RedOrderService redOrderService;

    /**
     * 获取保存在redis中的订单对应的桩信息然后判断是否离线，如果不离线就读取充电过程中的信息
     */
    public void run() {
        logger.info("redis自动扫描订单开始执行....");
        try {
            //boolean bool = redisService.addExpire(PlatformTaskEnum.EVC_CURRENT_ORDER_TASK.getCode(), 1, 10000);
            //if (bool) {
            //    logger.info("定时请求正在充电的桩的充电数据!!,不能重复执行");
            //    return;
            //}

            //保证原子性
            if (!redisService.setIfAbsent(PlatformTaskEnum.EVC_CURRENT_ORDER_TASK.getCode(), 1, 10000L)) {
                logger.info("每1分钟自动重新结算失败的订单接口在执行!!,不能重复执行");
                return;
            }

            //是否开启执行
            PlatformTaskSetting platformTaskSetting = platformTaskSettingService.selectByTaskType(PlatformTaskEnum.SEND_TICKET_TASK.getCode());
            if (platformTaskSetting == null) {
                logger.info("暂停执行定时请求正在充电的数据!");
                return;
            }

            List<RedOrder> list = (List<RedOrder>) redisService.getObjects(new RedOrder());

            for (RedOrder order : list) {
                if (order.getOrderNum() == null) {
                    return;
                }
                OrderInfo eOrder = orderInfoService.selectByOrderNum(order.getOrderNum());
                if (eOrder == null) {
                    logger.info("CurrentOrderJob redis中的订单号不存在:{}", order.getOrderNum());
                    continue;
                }

                ElecPile pile = elecPileMapper.selectByPrimaryKey(eOrder.getElecPileId());
                ElecGun gun = elecGunMapper.selectByPrimaryKey(eOrder.getElecGunId());
                MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(eOrder.getMemberId());

                if (HlhtOrderStatusEnum.HlhtOrderStatus2.getCode().equals(eOrder.getStatus())) {
                    logger.info("CurrentOrderJob 订单已结算:{}, 将清理redis缓存数据", order.getOrderNum());

                    //删除订单存留redis
                    redOrderService.removeOrder(pile.getPileRtua(), gun.getGunNum(), eOrder.getOrderNum());
                    redOrderService.removeOrder(pile.getPileRtua(), gun.getGunNum(), memberInfo.getMobile());

                    redChargeDataService.clearAllDate(pile.getPileRtua(), gun.getGunNum(), eOrder.getOrderNum());
                    continue;
                }

                //todo 智充平台不参与两分钟异常结算
                TenantManufacturer tenantManufacturer = tenantManufacturerService.selectByPrimaryKey(pile.getManufacturerId());
                if (tenantManufacturer != null && ZC_OPERATORID.equals(tenantManufacturer.getTenantCode())) {
                    continue;
                }


                if (PileVersionEnum.getPileVersionEnumResult(pile.getProgramVersion())) {
                    logger.warn("不会执行停止结算任务,对应桩编号:{},版本号:{},", pile.getPileNo(), pile.getProgramVersion());
                    continue;
                }
                if ("234".equals(pile.getProgramVersion())) {
                    //不会添加结算定时器
                    logger.warn("hjl离线不会添加结算定时器，桩编号:{}", pile.getPileNo());
                    continue;
                }
                ////派诺101  新亚232,260
                //if ("232".equals(pile.getProgramVersion()) || "101".equals(pile.getProgramVersion())) {
                //    logger.warn("不会执行停止结算任务,对应桩编号:{},", pile.getPileNo());
                //    continue;
                //} else if ("260".equals(pile.getProgramVersion()) || "102".equals(pile.getProgramVersion())) {
                //    logger.warn("不会执行停止结算任务,对应桩编号:{},", pile.getPileNo());
                //    continue;
                //} else if ("311".equals(pile.getProgramVersion())) {
                //    //不会添加结算定时器
                //    logger.warn("hjl离线不会添加结算定时器，桩编号:{}", pile.getPileNo());
                //    continue;
                //}

                //获取最后上报A5的时间
                String timeValue = redChargeDataService.getChargeReportTime(pile.getPileRtua(), gun.getGunNum(), eOrder.getOrderNum());
                //没有时间键值，说明是旧的订单数据，不做处理;
                if (timeValue == null) {
                    continue;
                }
                Date date = DateHelper.stringToDate(timeValue, DateHelper.DATE_COMMON_FORMAT);
                if ((System.currentTimeMillis() - date.getTime()) / 1000 > 5 * 60) {
                    logger.info("平台扫描结算订单号为：{}", order.getOrderNum());

                    //记录停止方式
                    redChargeDataService.putStopMode(pile.getPileRtua(), gun.getGunNum(), memberInfo.getMobile(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);
                    //扫描结算
                    orderCostService.updateOrderCost(eOrder.getOrderNum(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);

                    //添加日志
                    chargedProcessLogAssemble.assembleChargedProcessLog(ChargePhaseEnum.SETTLED, eOrder);

                    //推送订单停止状态
                    notifyStopChargeResult.notifyOrderStop(order.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}